<?php

/**
 * ECSHOP 红包类型的处理
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: bonus.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}



if ($_REQUEST['act'] == 'list')
{
    
	admin_priv('advance');
    $list = get_advance_list();

    $smarty->assign('advance_list',   $list['item']);
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('record_count', $list['record_count']);
    $smarty->assign('page_count',   $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    
    $smarty->assign('full_page',    1);
    $smarty->assign('ur_here',      '预购券');
    $smarty->display('advance_list.htm');
}

/*------------------------------------------------------ */
//-- 列表翻页、排序
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'query')
{
    $list = get_advance_list();

    $smarty->assign('advance_list',   $list['item']);
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('record_count', $list['record_count']);
    $smarty->assign('page_count',   $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('advance_list.htm'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));
}

/*------------------------------------------------------ */
//-- 删除
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('advance');

    $id = intval($_GET['id']);

    $db->query("DELETE FROM " .$ecs->table('user_advance'). " WHERE advance_id='$id'");

    $url = 'advance.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{
    /* 检查权限 */
    admin_priv('advance');

    if (isset($_POST['checkboxes']))
    {
        $advance_id_list = $_POST['checkboxes'];

        if (isset($_POST['drop']))
        {
            $sql = "DELETE FROM " . $ecs->table('user_advance'). " WHERE advance_id " . db_create_in($advance_id_list);
            $db->query($sql);

            admin_log(count($advance_id_list), 'batch_remove', 'advance');

            clear_cache_files();

            $link[] = array('text' => '返回列表',
                'href' => 'advance.php?act=list');
            sys_msg('已成功删除'.count($advance_id_list).'张预购券', 0, $link);
        }

        /* 发邮件 */
        elseif (isset($_POST['mail']))
        {
            $count = send_bonus_mail($bonus_type_id, $bonus_id_list);
            $link[] = array('text' => $_LANG['back_bonus_list'],
                'href' => 'bonus.php?act=bonus_list&bonus_type='. $bonus_type_id);
            sys_msg(sprintf($_LANG['success_send_mail'], $count), 0, $link);
        }
    }
    else
    {
        sys_msg('没有选中项', 1);
    }
}

/*------------------------------------------------------ */
//-- 发送邮件
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'send_mail')
{
	/* 取得参数：红包id */
	$advance_id = intval($_REQUEST['advance_id']);
	if ($advance_id <= 0)
	{
		die('invalid params');
	}

	/* 取得红包信息 */
	include_once(ROOT_PATH . 'includes/lib_order.php');
	$bonus = bonus_info($advance_id);
	if (empty($bonus))
	{
		sys_msg('优惠券不存在');
	}

	/* 发邮件 */
	$count = send_bonus_mail($bonus['bonus_type_id'], array($bonus_id));

	$link[0]['text'] = '返回列表';
	$link[0]['href'] = 'bonus.php?act=bonus_list&bonus_type=' . $bonus['bonus_type_id'];

	sys_msg($count.'封邮件已成功发送', 0, $link);
}



/**
 * 获取用户预购券列表
 * @access  public
 * @param   $page_param
 * @return void
 */
function get_advance_list()
{
    /* 查询条件 */
    $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'advance_id' : trim($_REQUEST['sort_by']);
    $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

//     $where = empty($filter['bonus_type']) ? '' : " WHERE bonus_type_id='$filter[bonus_type]'";

    $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('user_advance'). $where;
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    /* 分页大小 */
    $filter = page_and_size($filter);

    $sql = "SELECT ua.*, u.user_name, o.order_sn ".
          " FROM ".$GLOBALS['ecs']->table('user_advance'). " AS ua ".
          " LEFT JOIN " .$GLOBALS['ecs']->table('users'). " AS u ON u.user_id=ua.user_id ".
          " LEFT JOIN " .$GLOBALS['ecs']->table('order_info'). " AS o ON o.order_id=ua.order_id ".
          " ORDER BY ".$filter['sort_by']." ".$filter['sort_order'].
          " LIMIT ". $filter['start'] .", $filter[page_size]";
    $row = $GLOBALS['db']->getAll($sql);

    foreach ($row AS $key => $val)
    {
        $row[$key]['used_time'] = $val['used_time'] == 0 ?
            '未使用' : local_date($GLOBALS['_CFG']['date_format'], $val['used_time']);
        $row[$key]['create_time'] = local_date($GLOBALS['_CFG']['date_format'], $val['create_time']);
        $row[$key]['emailed'] = ($row[$key]['emailed']==BONUS_NOT_MAIL)?'未发送':(($row[$key]['emailed']==BONUS_MAIL_SUCCEED)?'发送成功':'发送失败');
        $row[$key]['sms'] = ($row[$key]['sms']==BONUS_NOT_MAIL)?'未发送':(($row[$key]['sms']==BONUS_MAIL_SUCCEED)?'发送成功':'发送失败');
        $row[$key]['advance_price'] = $val['discount'];
    }

    $arr = array('item' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

/**
 * 取得红包类型信息
 * @param   int     $bonus_type_id  红包类型id
 * @return  array
 */
function bonus_type_info($bonus_type_id)
{
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('bonus_type') .
            " WHERE type_id = '$bonus_type_id'";

    return $GLOBALS['db']->getRow($sql);
}

/**
 * 发送红包邮件
 * @param   int     $bonus_type_id  红包类型id
 * @param   array   $bonus_id_list  红包id数组
 * @return  int     成功发送数量
 */
function send_bonus_mail($bonus_type_id, $bonus_id_list)
{
    /* 取得红包类型信息 */
    $bonus_type = bonus_type_info($bonus_type_id);
    if ($bonus_type['send_type'] != SEND_BY_USER)
    {
        return 0;
    }

    /* 取得属于该类型的红包信息 */
    $sql = "SELECT b.bonus_id, u.user_name, u.email " .
            "FROM " . $GLOBALS['ecs']->table('user_bonus') . " AS b, " .
                $GLOBALS['ecs']->table('users') . " AS u " .
            " WHERE b.user_id = u.user_id " .
            " AND b.bonus_id " . db_create_in($bonus_id_list) .
            " AND b.order_id = 0 " .
            " AND u.email <> ''";
    $bonus_list = $GLOBALS['db']->getAll($sql);
    if (empty($bonus_list))
    {
        return 0;
    }

    /* 初始化成功发送数量 */
    $send_count = 0;

    /* 发送邮件 */
    if ($bonus_type['type'] == BONUS_TYPE_DISCOUNT){
    	$tpl   = get_mail_template('send_bonus_discount');
    }else{
    	$tpl   = get_mail_template('send_bonus_money');
    }
    
    $today = local_date($GLOBALS['_CFG']['date_format']);
    foreach ($bonus_list AS $bonus)
    {
        $GLOBALS['smarty']->assign('user_name',    $bonus['user_name']);
        $GLOBALS['smarty']->assign('shop_name',    $GLOBALS['_CFG']['shop_name']);
        $GLOBALS['smarty']->assign('send_date',    $today);
        $GLOBALS['smarty']->assign('sent_date',    $today);
        $GLOBALS['smarty']->assign('count',        1);
        $GLOBALS['smarty']->assign('use_start',    local_date($GLOBALS['_CFG']['date_format'],$bonus_type['use_start_date']));
		$GLOBALS['smarty']->assign('use_end',    	local_date($GLOBALS['_CFG']['date_format'],$bonus_type['use_end_date']));
		$GLOBALS['smarty']->assign('money',        ($bonus_type['type'] == BONUS_TYPE_DISCOUNT)?$bonus_type['type_discount']:price_format($bonus_type['type_money']));

        $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
        
        if (send_mail($bonus['user_name'], $bonus['email'], $tpl['template_subject'], $content, $tpl['is_html']))
        {
            $sql = "UPDATE " . $GLOBALS['ecs']->table('user_bonus') .
                    " SET emailed = '" . BONUS_MAIL_SUCCEED . "'" .
                    " WHERE bonus_id = '$bonus[bonus_id]'";
            $GLOBALS['db']->query($sql);
            $send_count++;
        }
        else
        {
            $sql = "UPDATE " . $GLOBALS['ecs']->table('user_bonus') .
                    " SET emailed = '" . BONUS_MAIL_FAIL . "'" .
                    " WHERE bonus_id = '$bonus[bonus_id]'";
            $GLOBALS['db']->query($sql);
        }
    }

    return $send_count;
}

function add_to_maillist($username, $email, $subject, $content, $is_html)
{
    $time = time();
    $content = addslashes($content);
    $template_id = $GLOBALS['db']->getOne("SELECT template_id FROM " . $GLOBALS['ecs']->table('mail_templates') . " WHERE template_code = 'send_bonus'");
    $sql = "INSERT INTO "  . $GLOBALS['ecs']->table('email_sendlist') . " ( email, template_id, email_content, pri, last_send) VALUES ('$email', $template_id, '$content', 1, '$time')";
    $GLOBALS['db']->query($sql);
    return true;
}

?>